package com.sf.dlb.web.service;


import com.sf.dlb.bean.UserReportRequestBean;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.mapper.dao.ChartMapper;

import com.sf.dlb.utils.*;
import com.sf.dlb.vo.*;
import com.sf.dlb.web.config.Global;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by jing.tan on 2018/12/10.
 */
@Service
public class ChartService {
    private static Logger logger= LoggerFactory.getLogger(ChartService.class);

    @Autowired
    private Global global;
    @Autowired
    private ChartMapper chartMapper;
    /**
     * 用户基础分析
     * @return
     */
    public ResultVO userInfoReport(UserReportRequestBean userReportRequestBean){
        //时间处理；
        Date startTimeD=DateUtils.onKeepDate(userReportRequestBean.getStartTimeD());
        Date endTimeD=DateUtils.onKeepDate(userReportRequestBean.getEndTimeD());
        userReportRequestBean.setStartTimeD(DateUtils.addDays(startTimeD,-1));
        userReportRequestBean.setEndTimeD(DateUtils.addDays(endTimeD,1));
//      APP用户增长分析
        List<Map> userIncreaseMap=userIncreaseReport(userReportRequestBean);
        Integer historyUserCount=chartMapper.findByUserCount("0");
        historyUserCount=(historyUserCount==null?0:historyUserCount);
        int userIncreaseTotal = 0;
        String timeSpan="";
        UserBaseReportVO.NewUsersBean.DataBean1 dataBean1=new UserBaseReportVO.NewUsersBean.DataBean1();
        ArrayList<String> dataBean1XAxis=new ArrayList<>();
        ArrayList<Integer> dataBean1YAxis=new ArrayList<>();
        UserBaseReportVO.NewUsersBean newUsersBean=new UserBaseReportVO.NewUsersBean();
        for (Map map:userIncreaseMap) {
            String date= (String) map.get("date");
            Long userCount= (Long) map.get("userCount");
            int userCountI=userCount!=null?userCount.intValue():0;
            dataBean1XAxis.add(date);
            dataBean1YAxis.add(userCountI);
            userIncreaseTotal+=userCountI;
        }
        String startTimeStr=DateUtils.formatDate(startTimeD,"yyyy-MM-dd");
        String endTimeStr=DateUtils.formatDate(endTimeD,"yyyy-MM-dd");
        timeSpan=startTimeStr+" - "+endTimeStr;
        dataBean1.setxAxis(dataBean1XAxis);
        dataBean1.setyAxis(dataBean1YAxis);
        newUsersBean.setName("APP用户增长");
        newUsersBean.setTotal(userIncreaseTotal);
        newUsersBean.setHistory(historyUserCount);
        newUsersBean.setTimespan(timeSpan);
        newUsersBean.setData(dataBean1);

//      用户喜好分析
        List<Map> userNewClassMap=userNewClassReport(userReportRequestBean);
        Long historyUserNewClass= chartMapper.findByUserNewClassReportTotal("0","1");
        historyUserNewClass=(historyUserNewClass==null?0:historyUserNewClass);
        int userNewClassTotal = 0;
        ArrayList<String> userNewClassXAxis=new ArrayList<>();
        List<UserBaseReportVO.OrderAnalysisBean.DataBean2> dataBean2=new ArrayList<>();
        UserBaseReportVO.OrderAnalysisBean orderAnalysisBean=new UserBaseReportVO.OrderAnalysisBean();
        for (Map map:userNewClassMap) {
            String classId= (String) map.get("classId");
            String className= (String) map.get("className");
            Long classCount= (Long) map.get("classCount");
            int classCountI=(classCount!=null?classCount.intValue():0);
            userNewClassXAxis.add(className);
            UserBaseReportVO.OrderAnalysisBean.DataBean2 dataBean21=new UserBaseReportVO.OrderAnalysisBean.DataBean2();
            dataBean21.setName(className);
            dataBean21.setValue(classCountI);
            dataBean2.add(dataBean21);
            userNewClassTotal+=classCountI;
        }
        orderAnalysisBean.setName("APP用户喜好");
        orderAnalysisBean.setTotal(userNewClassTotal);
        orderAnalysisBean.setHistory(historyUserNewClass.intValue());
        orderAnalysisBean.setTimespan(timeSpan);
        orderAnalysisBean.setxAxis(userNewClassXAxis);
        orderAnalysisBean.setData(dataBean2);

//      用户收益分析
        List<Map> userGetDlbMap=userGetDlbReport(userReportRequestBean);
        Double historyGetDlbCount=chartMapper.findByGetDlbTotal("0","1");
        historyGetDlbCount=(historyGetDlbCount==null?0.0:historyGetDlbCount);
        Double userGetDlbTotal =0.0;
        UserBaseReportVO.TokenBean.DataBean dataBean=new UserBaseReportVO.TokenBean.DataBean();
        ArrayList<String> dataBeanXAxis=new ArrayList<>();
        ArrayList<Double> dataBeanYAxis=new ArrayList<>();
        UserBaseReportVO.TokenBean tokenBean=new UserBaseReportVO.TokenBean();
        for (Map map:userGetDlbMap) {
            String date= (String) map.get("date");
            BigDecimal dlbSum= (BigDecimal) map.get("dlbSum");
            Double dlbSumD=(dlbSum!=null?dlbSum.doubleValue():0.0);
            dataBeanXAxis.add(date);
            dataBeanYAxis.add(dlbSumD);
            userGetDlbTotal=Arith.add(userGetDlbTotal,dlbSumD);
        }
        dataBean.setxAxis(dataBeanXAxis);
        dataBean.setyAxis(dataBeanYAxis);
        tokenBean.setName("APP用户收益");
        tokenBean.setTotal(userGetDlbTotal);
        tokenBean.setHistory(historyGetDlbCount);
        tokenBean.setTimespan(timeSpan);
        tokenBean.setData(dataBean);

//      阅读时长分析
        List<Map> userReaderTimeMap=userReaderTimeReport(userReportRequestBean);
        Long historyUserReaderTime=chartMapper.findByUserReaderTimeReportTotal("0","1");
        historyUserReaderTime=(historyUserReaderTime==null?0:historyUserReaderTime);
        int userReaderTimeTotalI =0;
        UserBaseReportVO.ReadTimeBean.DataBean3 dataBean3=new UserBaseReportVO.ReadTimeBean.DataBean3();
        ArrayList<String> dataBean3XAxis=new ArrayList<>();
        ArrayList<Integer> dataBean3YAxis=new ArrayList<>();
        UserBaseReportVO.ReadTimeBean readTimeBean=new UserBaseReportVO.ReadTimeBean();
        for (Map map:userReaderTimeMap) {
            String date= (String) map.get("date");
            BigDecimal timeSum= (BigDecimal) map.get("timeSum");
            int timeSumI=(timeSum!=null?timeSum.intValue():0);
            dataBean3XAxis.add(date);
            dataBean3YAxis.add(timeSumI);
            userReaderTimeTotalI+=timeSumI;
        }
        dataBean3.setxAxis(dataBean3XAxis);
        dataBean3.setyAxis(dataBean3YAxis);
        readTimeBean.setName("APP阅读时长");
        readTimeBean.setTotal(DateUtils.timeFormatHourAndMin(userReaderTimeTotalI));
        readTimeBean.setHistory(DateUtils.timeFormatDayAndHourAndMin(historyUserReaderTime));
        readTimeBean.setTimespan(timeSpan);
        readTimeBean.setData(dataBean3);
        //封装VO
        UserBaseReportVO userBaseReportVO=new UserBaseReportVO();
        userBaseReportVO.setNewUsers(newUsersBean);
        userBaseReportVO.setOrderAnalysis(orderAnalysisBean);
        userBaseReportVO.setToken(tokenBean);
        userBaseReportVO.setReadTime(readTimeBean);
        return ResultVOUtil.success(userBaseReportVO);
    }
    /**
     * APP用户增长分析
     */
    public List<Map> userIncreaseReport(UserReportRequestBean userReportRequestBean){
        Date startTime=userReportRequestBean.getStartTimeD();
        Date endTime=userReportRequestBean.getEndTimeD();
        List<Map> maps=chartMapper.findByUserIncreaseReport(startTime,endTime,"0");
        return maps;
    }
    /**
     * 用户喜好分析：分析不同内容
     */
    public List<Map> userNewClassReport(UserReportRequestBean userReportRequestBean){
        Date startTime=userReportRequestBean.getStartTimeD();
        Date endTime=userReportRequestBean.getEndTimeD();
        List<Map> maps= chartMapper.findByUserNewClassReport(startTime, endTime, "0","1");
        return maps;
    }
    /**
     * 用户收益分析:
     */
    public List<Map> userGetDlbReport(UserReportRequestBean userReportRequestBean){
        Date startTime=userReportRequestBean.getStartTimeD();
        Date endTime=userReportRequestBean.getEndTimeD();
        List<Map> maps=chartMapper.findByUserGetDlbReport(startTime,endTime,"0","1");
        return maps;
    }
    /**
     * 阅读时长分析；
     */
    public List<Map> userReaderTimeReport(UserReportRequestBean userReportRequestBean){
        Date startTime=userReportRequestBean.getStartTimeD();
        Date endTime=userReportRequestBean.getEndTimeD();
        List<Map> maps=chartMapper.findByUserReaderTimeReport(startTime,endTime,"0","1");
        return maps;
    }


    /**
     * 1-DLB发放状态-饼图
     */
    public ResultVO giveOutDlbPie() {
        Map map=chartMapper.findByGiveOutDlb();
        if(null==map){
            logger.info(" giveOutDlbPie  DLB发放状态暂无数据 ");
            return ResultVOUtil.error(ResponseConstant.ERROR,"DLB发放状态暂无数据");
        }
        BigDecimal lockDlb= (BigDecimal) map.get("lock_dlb");
        BigDecimal unlockDlb=(BigDecimal) map.get("unlock_dlb");
        BigDecimal availableDlb=(BigDecimal) map.get("available_dlb");
        Double total=Arith.add(Arith.add(lockDlb.doubleValue(),unlockDlb.doubleValue()),availableDlb.doubleValue());

        ArrayList<String> xAxis=new ArrayList();
        xAxis.add("已锁定");
        xAxis.add("解锁中");
        xAxis.add("可用");
        ArrayList<UserBaseReportVO.OrderAnalysisBean.DataBean2> dataList=new ArrayList();
        dataList.add(new UserBaseReportVO.OrderAnalysisBean.DataBean2("已锁定",lockDlb.intValue()));
        dataList.add(new UserBaseReportVO.OrderAnalysisBean.DataBean2("解锁中",unlockDlb.intValue()));
        dataList.add(new UserBaseReportVO.OrderAnalysisBean.DataBean2("可用",availableDlb.intValue()));

        UserBaseReportVO.OrderAnalysisBean orderAnalysisBean=new UserBaseReportVO.OrderAnalysisBean();
        orderAnalysisBean.setxAxis(xAxis);
        orderAnalysisBean.setData(dataList);
        orderAnalysisBean.setHistory(0);
        orderAnalysisBean.setName("DLB发放状态");
        orderAnalysisBean.setTimespan("");
        orderAnalysisBean.setTotal(total.intValue());
        logger.info("giveOutDlbPie end orderAnalysisBean={}",GsonUtils.getInstance().toJson(orderAnalysisBean));
        return ResultVOUtil.success(orderAnalysisBean);
    }
    /**
     * 2-未来30天解锁分布图-折线
     */
    public ResultVO unlockDistributionBrokenLine() {
        Date currentDate=new Date();
        String currentStr=DateUtils.formatDate(currentDate,"yyyy-MM-dd");
        String endDateStr=DateUtils.addTimeByDay(currentDate,31);
        Date startTime=DateUtils.parseDate(currentStr);
        Date endTime=DateUtils.parseDate(endDateStr);
        String timeSpan=currentStr+" - "+endDateStr;
        List<Map> mapList=chartMapper.findByUnlockDistributionAndDay(startTime,endTime,global.wallet_dlb_unlock_time_day);
        ArrayList<String> dataBeanXAxis=new ArrayList<>();
        ArrayList<Double> dataBeanYAxis=new ArrayList<>();
        Double total=0.0;
        for (Map map:mapList) {
            String lockDate=map.get("lock_date").toString();
            String lockCountStr=map.get("lock_count").toString();
            Double lockCount=Double.valueOf(lockCountStr);
            dataBeanXAxis.add(lockDate);
            dataBeanYAxis.add(lockCount);
            total+=lockCount;
        }
        UserBaseReportVO.TokenBean.DataBean dataBean=new UserBaseReportVO.TokenBean.DataBean();
        dataBean.setyAxis(dataBeanYAxis);
        dataBean.setxAxis(dataBeanXAxis);

        UserBaseReportVO.TokenBean tokenBean=new UserBaseReportVO.TokenBean();
        tokenBean.setData(dataBean);
        tokenBean.setHistory(0);
        tokenBean.setName("未来30天解锁分布图");
        tokenBean.setTimespan(timeSpan);
        tokenBean.setTotal(total.intValue());
        logger.info("unlockDistributionBrokenLine end tokenBean={}",GsonUtils.getInstance().toJson(tokenBean));
        return ResultVOUtil.success(tokenBean);
    }
    /**
     * 3-实名状态-饼图
     */
    public ResultVO realStatePie() {
        List<Map> mapList=chartMapper.findByRealState();
        ArrayList<String> xAxis=new ArrayList();
        ArrayList<UserBaseReportVO.OrderAnalysisBean.DataBean2> dataList=new ArrayList();
        Double total=0.0;
        for (Map map:mapList) {
            String state=map.get("state").toString();
            String countS=map.get("count").toString();
            int count=Integer.parseInt(countS);
            String stateValue=StateToValueUtils.switchRealStateValue(state);
            xAxis.add(stateValue);
            dataList.add(new UserBaseReportVO.OrderAnalysisBean.DataBean2(stateValue,count));
            total+=count;
        }
        UserBaseReportVO.OrderAnalysisBean orderAnalysisBean=new UserBaseReportVO.OrderAnalysisBean();
        orderAnalysisBean.setxAxis(xAxis);
        orderAnalysisBean.setData(dataList);
        orderAnalysisBean.setHistory(0);
        orderAnalysisBean.setName("实名状态");
        orderAnalysisBean.setTimespan("");
        orderAnalysisBean.setTotal(total.intValue());
        logger.info("realStatePie end orderAnalysisBean={}",GsonUtils.getInstance().toJson(orderAnalysisBean));
        return ResultVOUtil.success(orderAnalysisBean);
    }

}
